import { Button, Form, Input, Radio, Select, Upload, Modal, Card, Space, Typography, Row, Col, Image, Switch, message } from "antd";
import { useState, useEffect } from "react";
import { PlusOutlined, EyeOutlined, InfoOutlined, MinusOutlined, SaveOutlined } from "@ant-design/icons";
import { Add_Employee, Get_Dept, Get_DeptByPost } from "../../service/organization"; // 导入新增员工的API

const { TextArea, Text } = Typography;

// 头像上传常量配置
const MAX_AVATAR_IMAGES = 1; // 头像最多上传1张
const ACCEPT_IMAGE_TYPES = ["image/jpeg", "image/png", "image/jpg"]; // 支持的图片格式
const MAX_IMAGE_SIZE = 5 * 1024 * 1024; // 图片最大限制5MB

// 获取Base64图片
const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });

// 图片上传前的校验
const beforeUpload = (file, maxSize = 5) => {
  const isImage = ACCEPT_IMAGE_TYPES.includes(file.type);
  if (!isImage) {
    Modal.error({
      title: "格式错误",
      content: "请上传 JPG、JPEG 或 PNG 格式的图片",
    });
    return false;
  }

  const isLtMaxSize = file.size <= MAX_IMAGE_SIZE;
  if (!isLtMaxSize) {
    Modal.error({
      title: "大小超限",
      content: `图片大小不能超过 ${maxSize}MB，请重新选择`,
    });
    return false;
  }

  return true;
};

// 递归函数：将嵌套的部门结构扁平化为一维数组
const flattenDepartments = (departments) => {
  let result = [];
  departments.forEach(dept => {
    // 添加当前部门
    result.push(dept);
    // 如果有子部门，递归处理并合并结果（不区分父子级）
    if (dept.children && dept.children.length > 0) {
      result = result.concat(flattenDepartments(dept.children));
    }
  });
  return result;
};

export const AddEmployee = (props) => {

  // 表单实例
  const [empForm] = Form.useForm();
  // 头像上传相关状态
  const [avatarFileList, setAvatarFileList] = useState([]); // 头像文件列表
  const [previewImage, setPreviewImage] = useState(""); // 预览图片地址
  const [previewOpen, setPreviewOpen] = useState(false); // 预览弹窗显隐
  const [loading, setLoading] = useState(false); // 提交加载状态

// 部门下的岗位
  const [duty, setDuty] = useState(null);

  const [departments, setDepartments] = useState([]); // 部门列表数据（扁平结构）

  // 获取部门数据并处理为扁平结构
  useEffect(() => {
    const bind_dept = async () => {
      try {
        const res = await Get_Dept();

        // 将嵌套的部门结构转换为扁平结构，不区分父子级
        const flatDepartments = flattenDepartments(res.data);
        setDepartments(flatDepartments);
      } catch (error) {
        console.error("获取部门数据失败:", error);
        Modal.error({
          title: "数据加载失败",
          content: "获取部门列表时发生错误，请稍后重试",
        });
      }
    };

     const bind_dept_post = async () => {
     
      // 实现获取岗位的逻辑
      const res=await Get_DeptByPost({id:props.data.id});
      if(res.code==0){
       
        setDuty(res.data.map((d)=>({
          value:d.id,
          label:d.name
        })));
      }
    }
    bind_dept_post();

    bind_dept();
   

    // 若id存在（编辑/指定部门场景），将id和名称回显到表单
    if (props.data.id) {
      empForm.setFieldsValue({
        deptId: props.data.id,       // 存储部门ID
        deptName: props.data.name    // 存储部门名称
      });
    }
  }, [props.data, empForm]);

  
  // 处理图片预览
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
  };

  // 处理头像上传变更
 // 处理头像上传变更
const handleAvatarChange = ({ file, fileList: newFileList }) => {
  // 过滤掉已移除的文件并限制数量
  const filteredList = newFileList
    .filter((f) => f.status !== "removed")
    .slice(0, MAX_AVATAR_IMAGES); // 只保留第一张
  setAvatarFileList(filteredList);

  // 上传成功时，从响应中提取URL并存入表单
  if (file && file.status === "done") {
    // 检查响应是否包含url字段
    if (file.response && file.response.code === 0 && file.response.url) {
      empForm.setFieldsValue({
        avatar: file.response.url, // 将接口返回的URL存入表单
      });
    } else {
      Modal.error({
        title: "上传失败",
        content: file.response?.message || "获取图片URL失败，请重新上传",
      });
    }
  } else if (file && file.status === "error") {
    Modal.error({
      title: "上传错误",
      content: "图片上传失败，请稍后重试",
    });
  }
};
  // 上传按钮通用组件
  const renderUploadButton = (text, icon = <PlusOutlined />) => (
    <button style={{ border: 0, background: "none" }} type="button">
      {icon}
      <div style={{ marginTop: 8 }}>{text}</div>
    </button>
  );

  // 新增员工
  const add = async () => {
    
      setLoading(true);
      // 验证并获取表单数据（包含头像URL、部门ID等）
      const formData = await empForm.validateFields();

      const employeeData = {
        ...formData,

        deptId: props.data.id, // 添加父级id

      };

     
      // 调用后端接口提交数据
     const response = await Add_Employee(employeeData);

      if (response.code == 0) {
         setLoading(false);
       message.info(response.message);
        // 提交成功后重置表单和文件列表
        empForm.resetFields();
        setAvatarFileList([]);
       
        // 通知父组件员工已添加，刷新列表
        props.onEmpAdded();
      }
   
  };


  return (
    <>
      <div className="modal-box">
        <Text type="secondary" style={{ marginBottom: 20, display: "block", fontSize: "13px" }}>
          请填写员工信息，带 <span style={{ color: "#ff4d4f" }}>*</span> 为必填项
        </Text>

        <Form form={empForm} layout="vertical" scrollToFirstError
          initialValues={{ avatar: "", deptId: "", deptName: "", gender: true }}>
          {/* 基本信息卡片 */}
          <Card
            style={{
              marginBottom: 20,
              borderRadius: "8px",
              borderColor: "#e8e8e8",
              boxShadow: "0 1px 2px rgba(0, 0, 0, 0.05)",
              borderLeft: "3px solid #1890ff",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                marginBottom: 16,
                color: "#1f2329",
              }}
            >
              <InfoOutlined style={{ marginRight: 8, color: "#1890ff" }} />
              <Typography.Title level={5} style={{ margin: 0 }}>
                基本信息
              </Typography.Title>
            </div>

            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12}>
                <Form.Item
                  name="name"
                  label="姓名"
                  rules={[{ required: true, message: "请输入姓名" }]}
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  <Input placeholder="请输入姓名" style={{ borderRadius: "6px" }} />
                </Form.Item>
              </Col>

              <Col xs={24} sm={12}>
                <Form.Item
                  name="gender"
                  label="性别"
                  rules={[{ required: true, message: "请选择性别" }]}
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  <Switch checkedChildren="男" unCheckedChildren="女" defaultChecked />
                </Form.Item>
              </Col>

              <Col xs={24} sm={12}>
                <Form.Item
                  name="phone"
                  label="联系电话"
                  rules={[
                    { required: true, message: "请输入联系电话" },
                    { pattern: /^1[0-9]\d{9}$/, message: "请输入正确的手机号码" },
                  ]}
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  <Input maxLength={11} placeholder="请输入联系电话" style={{ borderRadius: "6px" }} />
                </Form.Item>
              </Col>

              {/* 部门选择逻辑 - 显示部门名称 */}
              <Col xs={24} sm={12}>
                <Form.Item
                  name="deptName" // 存储部门ID（后端需要）
                  label="所属部门"
                  rules={[{ required: true, message: "请选择所属部门" }]}
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  {/* id为空（新增员工）：显示部门选择器；id存在（指定部门）：显示禁用的输入框 */}
                  {!props.data.id ? (
                    <Select
                      placeholder="请选择所属部门"
                      style={{ borderRadius: "6px", width: "100%" }}
                      showSearch // 支持搜索部门
                      optionFilterProp="label" // 按标签搜索

                    >
                      {departments.map((dept) => (
                        <Select.Option key={dept.key} value={dept.key} label={dept.title}>
                          {dept.title} {/* 显示部门名称 */}
                        </Select.Option>
                      ))}
                    </Select>
                  ) : (
                    <Input
                      disabled
                      value={props.data.name} // 直接显示部门名称
                      style={{ borderRadius: "6px" }}
                    />
                  )}
                </Form.Item>
              </Col>

              {/* 隐藏的部门名称字段，用于存储选择的部门名称 */}
              <Form.Item name="deptName" hidden>
                <Input />
              </Form.Item>

              <Col xs={24} sm={12}>
                <Form.Item
                  name="postId"
                  label="职称/岗位"
                  rules={[{ required: true, message: "请选择职称/岗位" }]}
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  <Radio.Group
                    options={duty}
                    optionType="button" // 按钮式单选，视觉更友好
                    buttonStyle="solid"
                    style={{ borderRadius: "6px" }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Card>

          {/* 头像信息卡片 */}
          <Card
            style={{
              marginBottom: 20,
              borderRadius: "8px",
              borderColor: "#e8e8e8",
              boxShadow: "0 1px 2px rgba(0, 0, 0, 0.05)",
              borderLeft: "3px solid #1890ff",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                marginBottom: 16,
                color: "#1f2329",
              }}
            >
              <InfoOutlined style={{ marginRight: 8, color: "#1890ff" }} />
              <Typography.Title level={5} style={{ margin: 0 }}>
                头像信息
              </Typography.Title>
            </div>

            <Row gutter={[16, 16]}>
              <Col xs={24}>
                {/* 头像图片上传区域 */}
                <Form.Item
                  name="avatar" // 存储头像URL的表单字段（隐藏，仅用于存储数据）
                  hidden
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  label={
                    <span>
                      员工头像 <span style={{ color: "#ff4d4f" }}>*</span>
                    </span>
                  }
                  rules={[{ required: true, message: "请上传员工头像" }]}
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                  style={{ marginBottom: 24 }}
                >
                  <div>
                    <Text type="secondary" style={{ fontSize: "13px", marginBottom: 12, display: "block" }}>
                      头像要求：请上传清晰的个人头像，支持JPG、PNG格式，大小不超过5MB
                    </Text>
                    <Upload
                      action="http://localhost:3268/api/Upload/Upload_Goods_Cover"
                      listType="picture-card"
                      fileList={avatarFileList}
                      onPreview={handlePreview}
                      onChange={handleAvatarChange}
                      beforeUpload={(file) => beforeUpload(file)}
                      maxCount={MAX_AVATAR_IMAGES}
                    >
                      {avatarFileList.length >= MAX_AVATAR_IMAGES ? null : renderUploadButton("上传头像")}
                    </Upload>
                    {/* 图片预览组件 */}
                    {previewImage && (
                      <Image
                        wrapperStyle={{ display: "none" }}
                        preview={{
                          visible: previewOpen,
                          onVisibleChange: (visible) => setPreviewOpen(visible),
                          afterOpenChange: (visible) => !visible && setPreviewImage(""),
                        }}
                        src={previewImage}
                      />
                    )}
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </Card>

          {/* 其他信息卡片 */}
          <Card
            style={{
              marginBottom: 20,
              borderRadius: "8px",
              borderColor: "#e8e8e8",
              boxShadow: "0 1px 2px rgba(0, 0, 0, 0.05)",
              borderLeft: "3px solid #1890ff",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                marginBottom: 16,
                color: "#1f2329",
              }}
            >
              <InfoOutlined style={{ marginRight: 8, color: "#1890ff" }} />
              <Typography.Title level={5} style={{ margin: 0 }}>
                其他信息
              </Typography.Title>
            </div>

            <Row gutter={[16, 16]}>
              {/* <Col xs={24}>
                <Form.Item
                  name="specialty"
                  label="擅长领域"
                  rules={[{ required: true, message: "请输入擅长领域" }]}
                  tooltip="多个领域请用逗号分隔"
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  <Input placeholder="请输入擅长领域，多个用逗号分隔" style={{ borderRadius: "6px" }} />
                </Form.Item>
              </Col> */}

              <Col xs={24}>
                <Form.Item
                  name="address"
                  label="住址"
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 24 }}
                >
                  <Input placeholder="请输入住址（可选）" style={{ borderRadius: "6px" }} />
                </Form.Item>
              </Col>
            </Row>
          </Card>

          {/* 操作按钮 */}
          <div
            style={{
              marginTop: 20,
              textAlign: "right",
              paddingTop: 16,
              borderTop: "1px solid #e8e8e8",
            }}
          >
            <Space size="middle">
              <Button
                onClick={() => props.onCancel?.()}
                style={{ borderRadius: "6px" }}
              >
                取消
              </Button>
              <Button
                type="primary"
                icon={<SaveOutlined />}
                onClick={add}
                loading={loading}
                style={{
                  borderRadius: "6px",
                  padding: "6px 16px",
                  boxShadow: "0 2px 4px rgba(24, 144, 255, 0.2)",
                }}
              >
                保存员工
              </Button>
            </Space>
          </div>
        </Form>
      </div>

      {/* 图片预览弹窗 */}
      <Modal
        open={previewOpen}
        title="头像预览"
        footer={null}
        onCancel={() => setPreviewOpen(false)}
        width={500}
      >
        <img
          src={previewImage}
          alt="预览"
          style={{ width: "100%", height: "auto", borderRadius: "4px" }}
        />
      </Modal>
    </>
  );
};
